<template>
  <div v-loading="loading" class="page-wrapper">
    <c-card title="设备列表" class="user-list">
      <el-button slot="func" type="primary" size="small" @click="showAddDlg">创建日志记录</el-button>
      <div class="search-row">
        <div>
          <div class="item">
            <label>日志记录类型</label>
            <el-select v-model="logType" size="small">
              <el-option :value="null" label="全部"></el-option>
              <el-option v-for="(d, i) in logTypeList" :key="i" :value="d" :label="d"></el-option>
            </el-select>
          </div>
          <div class="item">
            <label>站点</label>
            <el-select v-model="substationID" clearable size="small">
              <el-option v-for="s in subStations" :key="s.pkid" :value="s.pkid" :label="s.name"></el-option>
            </el-select>
          </div>
          <c-search
            v-model="devaccName"
            :height="32"
            :width="200"
            placeholder="设备名称"
            class="item"
            @submit="_getOrders"
          />
        </div>
      </div>
      <el-table ref="table" :data="orders" style="width: 100%">
        <el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
        <el-table-column prop="substationname" label="所属站点" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creator" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="logType" label="日志记录类型">
          <template v-slot="{row}">{{ row.logType }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row, $index}">
            <el-button size="small" type="text" @click="showDetailDlg(row)">查看</el-button>
            <el-button size="small" type="text" @click="deleteOrder(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getOrders"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg :visible.sync="dialogVisible" :title="disabled?'查看':'创建'">
      <el-form
        ref="form"
        :rules="rules"
        :model="newOrder"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="标题" prop="title">
              <el-input v-model="newOrder.title" :disabled="disabled" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="所属站点" prop="substationID">
              <el-select
                v-model="newOrder.substationID"
                size="small"
                :disabled="disabled"
                @change="stationsChange"
              >
                <el-option v-for="s in subStations" :key="s.pkid" :value="s.pkid" :label="s.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="日志类型" prop="logType">
              <el-select v-model="newOrder.logType" :disabled="disabled" size="small">
                <template v-for="(d, i) in logTypeList">
                  <el-option :key="i" :value="d" :label="d"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="抄送人" prop="copyPerson" @change="copyerChange">
              <el-select
                v-model="newOrder.copyPerson"
                :remote-method="getCopyer"
                :disabled="disabled"
                filterable
                remote
                size="small"
              >
                <el-option v-for="u in users" :key="u.pkid" :value="u.pkid" :label="u.username"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="日志记录内容" prop="contents">
              <el-input
                v-model="newOrder.contents"
                :disabled="disabled"
                size="small"
                type="textarea"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="备注" prop="note">
              <el-input
                v-model="newOrder.note"
                :disabled="disabled"
                size="small"
                type="textarea"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <el-form-item label="附件上传" prop="details" style="width: 100%">
            <el-upload
              :headers="headers"
              :file-list="newOrder.fileList"
              :limit="3"
              :on-success="changeHandler"
              :before-upload="beforeUpload"
              :on-remove="removeHandler"
              multiple
              accept=".png, .jpg, .jpeg, .doc, .docx, .xls, .xlsx"
              class="upload-demo"
              action="/api/plat/user/upload"
            >
              <el-button :disabled="disabled" size="small" type="primary">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button v-if="!disabled" type="danger" size="small" @click="createOrder">提交</el-button>
      </div>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import { calcPageNum } from "@/utils";
import CSearch from "@/components/CSearch";
export default {
  name: "RepairOrder",
  components: {
    CCard,
    CDlg,
    CSearch
  },
  data() {
    return {
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      loading: false,
      logType: null,
      substationID: null,
      devaccName: null,
      dialogVisible: false,
      orders: null,
      newOrder: {
        fileList: []
      },
      users: null,
      subStations: null,
      disabled: false,
      // select list
      logTypeList: ["设备预试定检记录", "设备巡检记录", "设备缺陷记录"],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        substationID: [
          { required: true, message: "请选择所属站点", trigger: "blur" }
        ],
        logType: [
          { required: true, message: "请选择日志类型", trigger: "blur" }
        ],
        contents: [
          { required: true, message: "请填写日志内容", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    headers() {
      return {
        Authorization: "Bearer " + this.$store.getters.token
      };
    }
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    this._getOrders();
    this.getSubStation();
  },
  methods: {
    _getOrders() {
      const devaccName = this.devaccName;
      const substationID = this.substationID;
      const logType = this.logType;
      const params = {
        page: this.page.index,
        rows: this.page.size,
        devaccName,
        substationID,
        logType
      };
      this.loading = true;
      return this.$axios
        .get("plat/isp/queryDevLog", { params })
        .then(res => {
          if (res.code === 1) {
            this.orders = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
    getCopyer(userName) {
      const params = {
        rows: 20,
        page: 1,
        userName: userName || ""
      };
      return this.$axios
        .get("/plat/user/queryUsers", { params })
        .then(res => {
          if (res.code === 1) {
            this.users = res.data.rows;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getSubStation() {
      return this.$axios
        .get("/plat/work/dropSubstation")
        .then(res => {
          if (res.code === 1) {
            this.subStations = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    showAddDlg() {
      this.dialogVisible = true;
      if (this.newOrder.pkid) {
        this.newOrder = {};
        this.disabled = false;
        this.$set(this.newOrder, "fileList", []);
      }
      this.getCopyer();
      // this.getSubStation();
    },
    createOrder() {
      return this.$refs["form"].validate(valid => {
        if (valid) {
          this.newOrder.appendix = JSON.stringify(
            this.newOrder.fileList.map(({ name, path }) => ({ name, path }))
          );
          return this.$axios
            .post("plat/isp/editDevLog", this.newOrder)
            .then(res => {
              if (res.code === 1) {
                this.$message.success("创建成功");
                this.dialogVisible = false;
                this._getOrders();
              } else {
                throw res.msg;
              }
            })
            .catch(e => this.$message.error(e));
        } else {
          return false;
        }
      });
    },
    deleteOrder(row) {
      return this.$confirm("是否继续删除记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return this.$axios
          .delete("plat/isp/deleteDevLog?pkid=" + row.pkid)
          .then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功!");
              this._getOrders();
            } else {
              throw res.msg;
            }
          })
          .catch(e => this.$message.error(e));
      });
    },
    stationsChange(v) {
      const name = this.subStations.filter(e => e.pkid === v)[0].name;
      this.$set(this.newOrder, "substationname", name);
    },
    copyerChange(v) {
      const name = this.users.filter(e => e.pkid === v)[0].username;
      this.$set(this.newOrder, "copyPerson", name);
    },
    showDetailDlg(row) {
      this.newOrder = row;
      this.disabled = true;
      this.dialogVisible = true;
      try {
        const list = JSON.parse(row.appendix);
        this.$set(row, "fileList", list);
      } catch (e) {
        this.$set(row, "fileList", []);
      }
    },
    changeHandler(response, file, fileList) {
      if (response.code === 1) {
        this.newOrder.fileList.push({
          name: file.name,
          status: "success",
          uid: file.uid,
          path: response.data
        });
      } else {
        return false;
      }
    },
    removeHandler(file, fileList) {
      this.$set(this.newOrder, "fileList", fileList);
    },
    beforeUpload(file) {
      const size = file.size / 1024;
      if (size > 500) {
        this.$message.error("文件不能大于100MB");
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
